package com.sise.bl.dao.impl;

import com.sise.bl.dao.OrdersDao;
import com.sise.bl.entity.Item;
import com.sise.bl.entity.Orders;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository(value = "ordersDao")
@SuppressWarnings("all")
public class OrdersDaoImpl extends BaseDaoImpl<Orders> implements OrdersDao {

    @Override
    public void insertOrders(Orders orders) {
        save(orders);
    }

    @Override
    public void insertItem(Item item) {
        this.getCurrentSession().save(item);
    }

    @Override
    public List<Orders> selectOrdersByUid(Integer uid) {
        String sql = "select o from Orders o join Address a on o.address.aid=a.aid " +
                "join User u on a.user.uid=u.uid " +
                "where a.user.uid=:uid";
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("uid",uid);
        List<Orders> orders = find(sql, params);
        return orders;
    }

    @Override
    public Orders selectOrdersByOid(String oid) {
        return get(oid);
    }

    @Override
    public void updateStateByOid(Orders orders) {
        update(orders);
    }

    @Override
    public List<Item> selectItemByOid(String oid) {
        String sql = "select i from Item i join Orders o on i.orders.oid=o.oid where i.orders.oid=:oid";
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("oid",oid);

        Query query = this.getCurrentSession().createQuery(sql);
        for (String key : params.keySet()) {
            query.setParameter(key, params.get(key));
        }
        List<Item> items = query.list();
        return items;
    }

    @Override
    public List<Orders> selectAll() {
        String sql = "from Orders";
        List<Orders> orders = find(sql);
        return orders;
    }

    @Override
    public void deleteOrders(Orders orders) {
        this.getCurrentSession().delete(orders);
    }

    @Override
    public void deleteOrdersByUid(Integer uid) {
        String sql = "delete from Orders o where o.user.uid="+uid;
        Query query = this.getCurrentSession().createQuery(sql);
        query.executeUpdate();
    }

    @Override
    public void deleteItemByOid(String oid) {
        String sql = "delete from Item i where i.orders.oid=?0";
        Query query = this.getCurrentSession().createQuery(sql);
        query.setParameter(0,oid);
        query.executeUpdate();
    }

    @Override
    public void deleteItemByPid(Integer pid) {
        String sql = "delete from Item i where i.product.pid=?0";
        Query query = this.getCurrentSession().createQuery(sql);
        query.setParameter(0,pid);
        query.executeUpdate();
    }
}
